package com.car.web.controller.index;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.car.dal.dao.department.TgDepartmentDao;
import com.car.dal.dao.notice.TgNoticeDao;
import com.car.dal.dao.period.TgPeriodDao;
import com.car.dal.dao.user.UserDao;
import com.car.dal.dao.user.UserinfoDao;
import com.car.dal.dao.usergroup.TgUsergroupDao;
import com.car.dal.object.TgNotice;
import com.car.dal.object.TgPeriod;
import com.car.dal.object.TgPower;
import com.car.dal.object.TgUser;
import com.car.dal.object.TgUsergroup;
import com.car.util.Base64;
import com.car.util.Constants;
import com.car.util.MD5;
import com.car.util.Result;
import com.car.util.ResultSupport;
import com.car.util.UserUtil;
import com.car.util.WebExecutor;
import com.car.util.WebExecutor.Biz;
import com.car.web.controller.base.BaseController;
import com.google.gson.Gson;

/**
 * 登录控制
 * 
 * @author Administrator
 * 
 */
@Controller
@RequestMapping("/sys")
public class LoginController extends BaseController {

	private static final Logger logger = Logger
			.getLogger(LoginController.class);
    @Resource
    private UserDao userDao;
    @Resource
    private TgUsergroupDao tgUsergroupDao;
    @Resource
    private TgDepartmentDao tgDepartmentDao;
    @Resource
    private UserinfoDao userinfoDao;
    @Resource
	private TgNoticeDao noticeDao;
    @Resource
    private TgPeriodDao tgPeriodDao;
	
	// 跳转到登录首页
	@RequestMapping(value = "/login")
	public ModelAndView login(ModelMap modelMap, final LoginVo loginVo,
			HttpServletRequest request, final HttpServletResponse response)
			throws Exception {
		modelMap = WebExecutor.execute(logger, loginVo, new Biz() {
			public Result process() {
				Result result = new ResultSupport(true);
				
				return result;
			}
		});
	
			// 跳转到登录页
			return new ModelAndView("login", modelMap);
	}

	
	// 登录操作
	@RequestMapping(value = "/adminlogin")
	public ModelAndView adminLogin(ModelMap modelMap, final LoginVo loginVo,
			final HttpServletRequest request, final HttpServletResponse response)
			throws Exception {
		String contextPath = request.getContextPath();
		modelMap = WebExecutor.execute(logger, loginVo, new Biz() {
			public Result process() {
				Result result = new ResultSupport(true);
				try {
						if (loginVo.getUser() != null&& loginVo.getPass()!=null) {
							// 根据登录名获取用户
							String inLoginName = loginVo.getUser().trim();
							TgUser hasuser=userDao.getTeacherByLoginName(inLoginName);
							
							// 用户存在,比较MD5密码,规则MD5(数据存储密码+验证码)
							if (null != hasuser) {
								
								String salt ="HKUUKOIIKJKLLI";
								String dbPasswordMd5 = MD5.md5(loginVo.getPass()
										+ salt);
								if (hasuser.getPassword().equals(dbPasswordMd5)) {
								
									// 保存用户登录后的cookies信息
									String loginame = hasuser.getUsername();
									// MD5加密用户详细信息
									String cookieValueWithMd5 = MD5
											.md5(loginame
													+ hasuser.getPassword());
									// 将要被保存的完整的Cookie值
									String cookieValue = loginame
											+ Constants.WORD_SEPARATOR
											+ cookieValueWithMd5;
									// 再一次对Cookie的值进行BASE64编码
									String cookieValueBase64 = new String(
											Base64.encode(cookieValue
													.getBytes()));
									// 开始保存Cookie
									Cookie cookie = new Cookie(
											Constants.DOMAIN_KEY,
											cookieValueBase64);
										cookie.setMaxAge(7 * 24 * 60 * 60);
									// String host =
									// request.getServerName();
									cookie.setPath("/");
//									cookie.setDomain(Config.getString(
//											"cookie.domain",
//											Config.getString("cookie.domain")));

									response.addCookie(cookie);
									// 设置登陆成功标志
									result.setDefaultModel(
											"isLoginSuccess", true);
									
									if(hasuser.getUsergroup()==9){
										result.setDefaultModel("url", "/sys/gotoindex_t.htm");
									}else{
										result.setDefaultModel("url", "/sys/gotoindex.htm");
									}

									if(hasuser.getLocked()==1){
										result.setDefaultModel("isLoginSuccess",false);
										result.setDefaultModel("message","账号被锁定，请联系管理员解锁。");
									}
									
								} else {
									// 登陆失败，密码不正确
									result.setDefaultModel("isLoginSuccess", false);
									result.setDefaultModel("message","密码不正确！");
								}
								
							} else {
								// 登陆失败，用户名不正确
								result.setDefaultModel("isLoginSuccess", false);
								result.setDefaultModel("message", "该用户不存在！");
							}

						} else {
							// 登陆失败，,没有登录输入验证，登录名，密码的提交
							result.setDefaultModel("message", "请输入用户名!");
							result.setDefaultModel("isLoginSuccess", false);
						}
						
						
					

				} catch (Exception e) {
					e.printStackTrace();
					result.FAILED(e.getMessage());
					logger.error(e.getMessage());
				}
				return result;
			}
		});
		// 控制跳转
		if ((Boolean) modelMap.get("isLoginSuccess")) {
				return new ModelAndView(new RedirectView(contextPath
						+ modelMap.get("url").toString()), null);
		} else {
			// 返回登录页面
			return new ModelAndView("login", modelMap);

		}
	}
	
	//OA后台
	@RequestMapping(value = "/gotoindex")
	public ModelAndView gotoindex(ModelMap modelMap, final LoginVo loginVo,
			final HttpServletRequest request, final HttpServletResponse response)
			throws Exception {
		modelMap = WebExecutor.execute(logger, loginVo, new Biz() {
			public Result process() {
				Result result = new ResultSupport(true);
				try {
 					TgPower tgPower = getPower();
 					result.setDefaultModel("tgPower", tgPower);
 					TgUser user = UserUtil.getUserFromCookies();
 					if(user.getType()!=null&&user.getType()==4){//type
 						TgPeriod period=new TgPeriod();
 						period.setType(6);
 						List<TgPeriod>list=tgPeriodDao.getPeriodByTime(period);
 						result.setDefaultModel("list",list);
 					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				return result;
			}
		});
		return new ModelAndView("/admin_index", modelMap);
	}
	
	//问卷后台
	@RequestMapping(value = "/gotoindex_t")
	public ModelAndView gotoindex_t(ModelMap modelMap, final LoginVo loginVo,
			final HttpServletRequest request, final HttpServletResponse response)
			throws Exception {
		modelMap = WebExecutor.execute(logger, loginVo, new Biz() {
			public Result process() {
				Result result = new ResultSupport(true);
				return result;
			}
		});
		return new ModelAndView("admin_t/admin_index", modelMap);
	}

	// 退出操作
	@RequestMapping(value = "/loginout")
	public ModelAndView loginout(ModelMap modelMap, final LoginVo loginVo,
			final HttpServletRequest request, final HttpServletResponse response)
			throws Exception {
		String contextPath = request.getContextPath();
		modelMap = WebExecutor.execute(logger, loginVo, new Biz() {
			public Result process() {
				Result result = new ResultSupport(true);
				try {
					// 删除cookie
					Cookie cookie = new Cookie(Constants.DOMAIN_KEY, "");
					cookie.setMaxAge(0);
					cookie.setPath("/");
					response.addCookie(cookie);
					result.setDefaultModel("user", null);
				} catch (Exception e) {
					e.printStackTrace();
					result.FAILED(e.getMessage());
					logger.error(e.getMessage());
				}
				return result;
			}
		});
		// 返回登录页面(页面重定向-重新请求)
		return new ModelAndView(new RedirectView(contextPath + "/sys/login.htm"), null);
	}
	
	public TgPower getPower() throws JSONException{
		//从浏览器中获取user
    	TgUser user = UserUtil.getUserFromCookies();
    	TgPower tgPower = null;
    	if(user!=null){
        	TgUsergroup tgUsergroup = new TgUsergroup();
        	tgUsergroup.setId(user.getUsergroup());
    		List<TgUsergroup> list = tgUsergroupDao.findByExample(tgUsergroup);
    		if(list!=null && list.size()>0){
    			Gson gson = new Gson();//new一个Gson对象
    			String power = list.get(0).getPower();
    			tgPower = gson.fromJson(power, TgPower.class);
    		}
    	}
    	return tgPower;
    }

	
}
